<template>
  <div>
    <span @click="onShowModal">
      <slot></slot>
    </span>

    <el-drawer
      size="80%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      v-model="visible"
    >
      <template #header>
        <div class="header">
          <div class="text">申请配件</div>
        </div>
      </template>
      <div v-loading="saveLoading">
        <div class="title_container">
          <h4 class="title_top">基本信息</h4>
        </div>
        <el-form label-position="right">
          <div class="basic_form">
            <div class="basic_form_item">
              <!-- 收货人姓名 -->
              <el-form-item label="收货人姓名" label-width="84">
                <el-input v-model="tableDataList.receiptName" clearable placeholder="收货人姓名" />
              </el-form-item>

              <!-- 收货人手机号 -->
              <el-form-item label="收货人手机号" label-width="84">
                <el-input
                  v-model="tableDataList.receiptPhone"
                  clearable
                  maxlength="11"
                  placeholder="收货人手机号"
                  @keyup="(e: Event) => (e.target as HTMLInputElement).value = (e.target as HTMLInputElement).value.replace(/[^\d]/g, '')"
                />
              </el-form-item>
            </div>

            <div class="basic_form_item">
              <!-- 申请类型 -->
              <el-form-item label="申请类型" label-width="96">
                <el-select
                  v-model="tableDataList.type"
                  clearable
                  placeholder="申请类型"
                  @change="handleChangeType"
                >
                  <el-option label="平台配件" :value="1" />
                  <el-option label="外部配件" :value="2" />
                </el-select>
              </el-form-item>

              <!-- 服务商配件类型 -->
              <el-form-item v-if="tableDataList.type == 2" label-width="96">
                <template #label>
                  <div style="white-space: nowrap">服务商配件类型</div>
                </template>

                <el-select
                  v-model="tableDataList.networkSpareType"
                  clearable
                  placeholder="服务商配件类型"
                >
                  <el-option label="服务商-外部仓配件" :value="1" />
                  <el-option label="工程师-外部仓配件" :value="2" />
                  <el-option label="自购备件" :value="3" />
                </el-select>
              </el-form-item>

              <!-- 收货地址类型 -->
              <el-form-item label="收货地址类型" label-width="96">
                <el-select
                  v-model="tableDataList.receiptAddrType"
                  clearable
                  placeholder="收货地址类型"
                  @change="handleChangeAddressType"
                  :disabled="tableDataList.type === 2"
                >
                  <el-option label="工单客户地址" :value="1" />
                  <el-option label="服务商地址" :value="2" />
                </el-select>
              </el-form-item>
            </div>

            <div class="basic_form_item">
              <!-- 收货人地址 -->
              <el-form-item label="收货人地址" label-width="72">
                <SingleAddress ref="addrsDom" :address="addrs" class="select_item" />
              </el-form-item>

              <!-- 详细地址 -->
              <el-form-item label="详细地址" label-width="72">
                <el-input
                  v-model="tableDataList.receiptAddress"
                  clearable
                  maxlength="200"
                  placeholder="收货人详细地址"
                  show-word-limit
                  size="small"
                  type="textarea"
                  resize="vertical"
                  :input-style="{
                    minHeight: '28px !important',
                    height: '28px',
                    maxHeight: '115px',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                  }"
                />
              </el-form-item>
            </div>
          </div>
        </el-form>
        <div class="table">
          <el-table
            :border="true"
            :data="tableDataList.spareMaterialVos"
            :row-class-name="tableRowClassName"
            resizable
            stripe
            max-height="700"
            @cell-mouse-enter="onCellMouseEnter"
            @cell-mouse-leave="onCellMouseLeave"
          >
            <!-- 操作 -->
            <el-table-column align="center" fixed="left" label="操作" width="75">
              <template #default="scope">
                <div v-show="styleColumn[scope.$index].tableColumnIndex">
                  <span>{{ scope.$index + 1 }}</span>
                </div>
                <div v-show="styleColumn[scope.$index].tableColumnBtn">
                  <span class="operation">
                    <el-icon class="icon" color="#007cff" size="16" @click="addItem">
                      <CirclePlus />
                    </el-icon>
                    <el-icon
                      class="icon"
                      color="rgba(245, 108, 108, 1)"
                      size="16"
                      @click="deleteItem(scope.$index)"
                    >
                      <RemoveFilled />
                    </el-icon>
                  </span>
                </div>
              </template>
            </el-table-column>

            <!-- 收支类型 -->
            <el-table-column label="收支类型" width="150">
              <template #default="scope">
                <el-select
                  v-model="scope.row.type"
                  @change="handleChangeIncomeOrPayType(scope.$index)"
                  placeholder="收支类型"
                >
                  <el-option label="商家承担" :value="1" />
                  <el-option label="平台承担" :value="2" />
                </el-select>
              </template>
            </el-table-column>

            <!-- 配件名称 -->
            <el-table-column label="配件名称" width="160">
              <template #default="scope">
                <el-select
                  v-model="scope.row.spareId"
                  :loading="loading2"
                  :filter-method="(val: string) => handleGetPartOptions(val)"
                  filterable
                  placeholder="请选择"
                  remote-show-suffix
                  @change="(id: string) => handleChangePart(id, scope.$index)"
                >
                  <el-option
                    v-for="item in partOptions"
                    :key="item.name"
                    :label="item.name"
                    :value="item.id"
                    @click="handlePartClick(item, scope.$index)"
                  />
                </el-select>
              </template>
            </el-table-column>

            <!-- 型号 -->
            <el-table-column label="型号" width="160" prop="model">
              <template #default="scope">
                <el-input v-model="scope.row.model" disabled />
              </template>
            </el-table-column>

            <!-- 规格 -->
            <el-table-column label="规格" width="140">
              <template #default="scope">
                <el-select
                  v-model="scope.row.specId"
                  :loading="loading2"
                  :filter-method="(val: string) => handleGetSpecOptions(val, scope.row.spareId, scope.$index)"
                  filterable
                  placeholder="请选择"
                  remote-show-suffix
                  @change="(id: string) => handleChangeSpec(id, scope.$index)"
                >
                  <el-option
                    v-for="item in scope.row.partSpecOptions"
                    :key="item.name"
                    :label="item.name"
                    :value="item.id"
                    @click="handlePartSpecClick(item, scope.$index)"
                  />
                </el-select>
              </template>
            </el-table-column>

            <!-- 规格编码 -->
            <el-table-column label="规格编码" width="160" prop="model">
              <template #default="scope">
                <el-input v-model="scope.row.specSku" disabled />
              </template>
            </el-table-column>

            <!-- 申请数量 -->
            <el-table-column label="申请数量" width="90">
              <template #default="scope">
                <el-input
                  v-model="scope.row.qty"
                  clearable
                  placeholder="数量"
                  @input="scope.row.qty = scope.row.qty.replace(/\D/g, '')"
                />
              </template>
            </el-table-column>

            <!-- 向服务商支付费用单价 -->
            <el-table-column label="向服务商支付费用单价" width="180">
              <template #default="scope">
                <el-input
                  clearable
                  v-model="scope.row.payNetworkPrice"
                  @keyup="(e: Event) => handlePayNetworkPricePriceInput(e, scope.$index)"
                  style="border-radius: 2px"
                >
                  <template #prepend>￥</template>
                </el-input>
              </template>
            </el-table-column>

            <!-- 收取商家费用单价 -->
            <el-table-column label="收取商家费用单价" width="180">
              <template #default="{ row, $index }">
                <el-input
                  clearable
                  v-model="row.receiveFactoryPrice"
                  :disabled="row.type !== 1"
                  @keyup="(e: Event) => handleReceiveFactoryPriceInput(e, $index)"
                  style="border-radius: 2px"
                >
                  <template #prepend>￥</template>
                </el-input>
              </template>
            </el-table-column>

            <!-- 平台承担费用单价 -->
            <el-table-column label="平台承担费用单价" width="180">
              <template #default="{ row, $index }">
                <el-input
                  clearable
                  v-model="row.price"
                  :disabled="row.type !== 2"
                  @keyup="(e: Event) => handlePriceInput(e, $index)"
                  style="border-radius: 2px"
                >
                  <template #prepend>￥</template>
                </el-input>
              </template>
            </el-table-column>

            <!-- 备注 -->
            <el-table-column label="备注" max-width="150" min-width="140">
              <template #default="scope">
                <el-input v-model="scope.row.remark" clearable placeholder="填写备注" />
              </template>
            </el-table-column>

            <!-- 附件 -->
            <el-table-column label="附件(最多上传8个)" width="460">
              <template #default="scope">
                <div class="updata_pic">
                  <el-dropdown v-for="(img, index) in scope.row.images" :key="index">
                    <el-image
                      class="img"
                      style="width: 40px; height: 40px"
                      :src="img.image"
                      :initial-index="index"
                      :preview-src-list="scope.row.images.map((item) => item.image)"
                      fit="scale-down"
                      preview-teleported
                    />
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click="handleDelFile(scope.$index, index)"
                          >删除</el-dropdown-item
                        >
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                  <el-upload
                    :auto-upload="false"
                    :on-change="(file: UploadFile) => handleUploadChange(file, scope.$index)"
                    :show-file-list="false"
                    v-if="scope.row.images.length < 8"
                    accept="image/*"
                    action="#"
                    list-type="picture-card"
                    multiple
                  >
                    <div class="plus_add">
                      <el-icon size="12">
                        <Plus />
                      </el-icon>
                    </div>
                  </el-upload>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="btns flex-justify-end" style="gap: 10px">
          <HButton isModal type="primary" @click="onSaveBtn">提交申请</HButton>
          <HButton isModal @click="onCancel">取消</HButton>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
  import { nextTick, ref } from 'vue'
  import { getOrderNetworkAddress, getWorkUserAddress, spareSaveOrder } from '@/api/parts'
  import { getOrderSparePageSelect, getOrderSpareSpecSelect } from '@/api/order'
  import { orderAnnexUpload } from '@/api/upload'
  import SingleAddress from '@/components/address/singleAddress.vue'
  import { ElMessage, UploadFile } from 'element-plus'
  import { checkNum, keepPartInteger, verifyPhone } from '@/utils/validate'
  import { CirclePlus, Plus, RemoveFilled } from '@element-plus/icons-vue'
  import _ from 'lodash'
  import { PartOptions, PartSpecOptions } from './types'
  import { OrderAPIRequestParam } from '@/typings/api/order'
  import HButton from '@/components/common/button/HButton.vue'

  const props = defineProps({
    workId: {
      type: String,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update-list'): void
  }>()

  /**
   * 获取费用详情
   * @param {number} index - 索引
   */
  const getSpareDetail = (index: number) => {
    return tableDataList.value.spareMaterialVos[index]
  }

  /**
   * 收支类型改变
   * @param {number} index - 操作的表格行的索引
   */
  const handleChangeIncomeOrPayType = (index: number) => {
    /**
     * 提取选择的规格的金额
     */
    let price = 0
    if (tableDataList.value.spareMaterialVos[index].specId) {
      const feeProject = tableDataList.value.spareMaterialVos[index].partSpecOptions.find(
        (module) => module.id === tableDataList.value.spareMaterialVos[index].specId,
      )
      price = getSpareDetail(index).overinsured ? feeProject.overPrice : feeProject.price
    }

    /**
     * 收支类型是商家承担
     * 将规格的金额填充到收取商家费用
     */
    if (getSpareDetail(index).type === 1 && !Number(getSpareDetail(index).receiveFactoryPrice)) {
      tableDataList.value.spareMaterialVos[index].receiveFactoryPrice = price
    }

    /**
     * 收支类型是商家承担
     * 将规格的金额填充到平台承担费用
     */
    if (getSpareDetail(index).type === 2 && !Number(getSpareDetail(index).price)) {
      tableDataList.value.spareMaterialVos[index].price = price
    }
  }

  // 弹窗的显示状态
  const visible = ref(false)

  /**
   * 显示弹窗方法
   */
  const onShowModal = async () => {
    await nextTick()
    getWorkUserAddressData()
    await getPartOptionsFn()
    visible.value = true
  }

  // 获取配件下拉选项请求参数
  const getPartOptionsParam = ref({
    limit: 0,
    name: '',
    page: 0,
  })

  // 配件下拉选项
  const partOptions = ref<Array<PartOptions>>([])

  /**
   * 获取配件下拉选项
   */
  const handleGetPartOptions = _.throttle((query: string) => {
    if (getPartOptionsParam.value.name === query) {
      return false
    }
    getPartOptionsParam.value.name = query
    getPartOptionsFn()
  }, 500)

  /**
   * 获取配件下拉选项方法
   */
  const getPartOptionsFn = async () => {
    loading2.value = true
    const res = await getOrderSparePageSelect(getPartOptionsParam.value, props.workId)
    if (res.data.code === 20000) {
      partOptions.value = res.data.data.rows
    } else {
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'error',
          duration: 3000,
        })
    }
    loading2.value = false
  }

  /**
   * 配件选择事件
   * @param {string} id - 配件id
   * @param {number} index - 操作的表格行的索引
   */
  const handleChangePart = async (id: string, index: number) => {
    tableDataList.value.spareMaterialVos[index].specId = null
    tableDataList.value.spareMaterialVos[index].specSku = ''
    tableDataList.value.spareMaterialVos[index].specName = ''
    if (id) {
      await getSpecOptionsFn(id, index)
    }
  }

  // 获取规格下拉选项请求参数
  const getSpecOptionsParam = ref({
    limit: 0,
    name: '',
    page: 0,
  })

  /**
   * 获取规格下拉选项
   */
  const handleGetSpecOptions = _.throttle((query: string, id: string, index: number) => {
    if (!id || getPartOptionsParam.value.name === query) {
      return
    }
    getPartOptionsParam.value.name = query
    getSpecOptionsFn(id, index)
  }, 500)

  /**
   * 获取规格下拉选项方法
   * @param {string} id - 配件id
   * @param {number} index - 操作的表格行的索引
   */
  const getSpecOptionsFn = async (id: string, index: number) => {
    loading2.value = true
    const res = await getOrderSpareSpecSelect(getSpecOptionsParam.value, id)
    if (res.data.success) {
      tableDataList.value.spareMaterialVos[index].partSpecOptions = res.data.data.rows
    } else {
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'error',
          duration: 3000,
        })
    }
    loading2.value = false
  }

  const loading2 = ref(false)
  const styleColumn = ref([
    {
      tableColumnBtn: false,
      tableColumnIndex: true,
    },
  ])

  const tableDataList = ref<OrderAPIRequestParam.ApplyOrCheckSpart>({
    delSpareMaterialIds: [], // 删除的工单配件物料对象
    id: null, // 工单备件ID，新增不必传，修改必传
    networkSpareType: 1, // 服务商配件类型：1-服务商-外部仓配件，2-工程师-外部仓配件，3-自购备件
    receiptAddrType: 1, // 收货地址类型：1-工单客户地址，2-服务商地址
    receiptAddress: '', // 收货人详细地址
    receiptArea: '', // 收货地址-县/区
    receiptCity: '', // 收货地址-市
    receiptName: '', // 收货人姓名
    receiptPhone: '', // 收货人手机号
    receiptProvince: '', // 收货地址-省
    receiptTown: '', // 收货地址-镇
    remark: '', // 备注
    spareMaterialVos: [
      // 工单配件物料对象
      {
        delImageIds: [], //	删除的工单费用图片对象ID
        id: null, // 配件物料ID，新增不必传，修改必传
        images: [], // 工单服务费用图片对象
        model: '', // 物料型号
        name: '', // 物料名称
        overinsured: true, // 物料质保状态：false-保内，true-保外
        payNetworkPrice: 0, // 	向服务商支付费用
        price: 0, // 物料单价
        qty: 1, // 物料数量
        receiveFactoryPrice: 0, // 收取商家费用
        remark: '', // 备注
        spareId: null, //	物料配件ID
        specId: null, // 物料配件规格ID
        specName: '', // 物料配件规格名称
        specSku: '', //商品规格编号
        type: 1, // 收支类型：1-向服务商支付，2-商家收取，3-平台承担
      },
    ],
    type: 1, // 申请类型：1-商家/总部配件，2-外部配件
    userOrNetworkId: null, // 用户/网点ID
    workId: null, // 工单ID
  })
  const addrsDom = ref()
  const addrs = ref({
    // 地址
    province: '',
    city: '',
    area: '',
    town: '',
  })

  // 给row对象赋索引值，注：在此赋值后，才可以在其他用到row的地址取值
  const tableRowClassName = ({ row, rowIndex }) => {
    row.index = rowIndex
  }
  // 鼠标移入事件
  const onCellMouseEnter = (row) => {
    styleColumn.value[row.index].tableColumnBtn = true
    styleColumn.value[row.index].tableColumnIndex = false
  }
  // 鼠标移出事件
  const onCellMouseLeave = (row) => {
    styleColumn.value[row.index].tableColumnBtn = false
    styleColumn.value[row.index].tableColumnIndex = true
  }

  // 添加
  function addItem() {
    const item = {
      delImageIds: [], //	删除的工单费用图片对象ID
      id: null, // 配件物料ID，新增不必传，修改必传
      images: [], // 工单服务费用图片对象
      model: '', // 物料型号
      name: '', // 物料名称
      overinsured: true, // 物料质保状态：false-保内，true-保外
      payNetworkPrice: 0, // 	向服务商支付费用
      price: 0, // 物料单价
      qty: 1, // 物料数量
      receiveFactoryPrice: 0, // 收取商家费用
      remark: '', // 备注
      spareId: null, //	物料配件ID
      specId: null, // 物料配件规格ID
      specName: '', // 物料配件规格名称
      specSku: '', //商品规格编号
      type: 1, // 收支类型：1-向服务商支付，2-商家收取，3-平台承担
    }
    tableDataList.value.spareMaterialVos.push(item)
    styleColumn.value.push({
      tableColumnIndex: true,
      tableColumnBtn: false,
    })
  }

  // 新增删除
  function deleteItem(n: number) {
    if (tableDataList.value.spareMaterialVos.length == 1) {
      return
    }
    tableDataList.value.spareMaterialVos = tableDataList.value.spareMaterialVos.filter(
      (o, index) => {
        return index != n
      },
    )
    styleColumn.value.splice(n, 1)
  }

  // 地址类型变化
  const handleChangeAddressType = (val: 1 | 2) => {
    addrsDom.value.getSelectAddr()
    switch (val) {
      case 1:
        getWorkUserAddressData()
        break
      case 2:
        getOrderNetworkAddressData()
        break
      default:
        tableDataList.value.receiptName = ''
        tableDataList.value.receiptPhone = ''
        tableDataList.value.receiptAddress = ''
        tableDataList.value.receiptProvince = ''
        tableDataList.value.receiptCity = ''
        tableDataList.value.receiptArea = ''
        tableDataList.value.receiptTown = ''
        addrs.value = {
          province: '',
          city: '',
          area: '',
          town: '',
        }
        addrsDom.value.clearSelectAddr()
        break
    }
  }

  /**
   * 获取用户地址
   */
  const getWorkUserAddressData = () => {
    getWorkUserAddress(props.workId).then((res) => {
      if (res.data.success) {
        tableDataList.value.userOrNetworkId = res.data.data.row.id
        tableDataList.value.receiptName = res.data.data.row.name
        tableDataList.value.receiptPhone = res.data.data.row.phone
        tableDataList.value.receiptAddress = res.data.data.row.address
        tableDataList.value.receiptProvince = res.data.data.row.province
        tableDataList.value.receiptCity = res.data.data.row.city
        tableDataList.value.receiptArea = res.data.data.row.area
        tableDataList.value.receiptTown = res.data.data.row.town
        addrs.value = {
          province: tableDataList.value.receiptProvince,
          city: tableDataList.value.receiptCity,
          area: tableDataList.value.receiptArea,
          town: tableDataList.value.receiptTown,
        }
      } else {
        if (res.data.isError)
          ElMessage({
            showClose: true,
            message: res.data.message,
            duration: 4000,
            offset: 200,
            type: 'error',
          })
      }
    })
  }

  /**
   * 获取服务商地址
   */
  const getOrderNetworkAddressData = () => {
    getOrderNetworkAddress(props.workId).then((res) => {
      if (res.data.success) {
        tableDataList.value.userOrNetworkId = res.data.data.row.id
        tableDataList.value.receiptName = res.data.data.row.name
        tableDataList.value.receiptPhone = res.data.data.row.phone
        tableDataList.value.receiptAddress = res.data.data.row.address
        tableDataList.value.receiptProvince = res.data.data.row.province
        tableDataList.value.receiptCity = res.data.data.row.city
        tableDataList.value.receiptArea = res.data.data.row.area
        tableDataList.value.receiptTown = res.data.data.row.town
        addrs.value = {
          province: tableDataList.value.receiptProvince,
          city: tableDataList.value.receiptCity,
          area: tableDataList.value.receiptArea,
          town: tableDataList.value.receiptTown,
        }
      } else {
        if (res.data.isError)
          ElMessage({
            showClose: true,
            message: res.data.message,
            duration: 4000,
            offset: 200,
            type: 'error',
          })
      }
    })
  }

  /**
   * 规格变化
   * @param {string} id - 规格id
   * @param {number} index - 操作的表格行的索引
   */
  const handleChangeSpec = (id: string, index: number) => {
    if (!id) {
      tableDataList.value.spareMaterialVos[index].specSku = ''
      tableDataList.value.spareMaterialVos[index].specName = ''
      tableDataList.value.spareMaterialVos[index].price = 0
    }
  }

  /**
   * 配件点击事件
   * @param {object} val - 配件的信息
   * @param {number} index - 操作的表格行的索引
   */
  const handlePartClick = (val: PartOptions, index: number) => {
    tableDataList.value.spareMaterialVos[index].model = val.model
    tableDataList.value.spareMaterialVos[index].name = val.name
    tableDataList.value.spareMaterialVos[index].price = 0
    tableDataList.value.spareMaterialVos[index].receiveFactoryPrice = 0
  }

  /**
   * 配件规格点击事件
   * @param {object} val - 规格信息
   * @param {number} index - 操作的表格行的索引
   */
  const handlePartSpecClick = (val: PartSpecOptions, index: number) => {
    tableDataList.value.spareMaterialVos[index].specSku = val.specSkuCode
    tableDataList.value.spareMaterialVos[index].specName = val.name
    const price = getSpareDetail(index).overinsured ? val.overPrice : val.price

    /**
     * 收支类型是商家收取
     * 将规格的金额填充到收取商家费用
     */
    if (getSpareDetail(index).type === 1 && !Number(getSpareDetail(index).receiveFactoryPrice)) {
      tableDataList.value.spareMaterialVos[index].receiveFactoryPrice = price
    }

    /**
     * 收支类型是平台承担
     * 将规格的金额填充到平台承担费用
     */
    if (getSpareDetail(index).type === 2 && !Number(getSpareDetail(index).price)) {
      tableDataList.value.spareMaterialVos[index].price = price
    }
  }

  /**
   * 保存时的加载
   */
  const saveLoading = ref(false)

  /**
   * 保存
   */
  async function onSaveBtn() {
    if (!verifyPhone(tableDataList.value.receiptPhone)) {
      ElMessage({
        type: 'warning',
        message: '手机号码格式不正确',
      })
      return false
    }

    let checkResult = true
    for (let i = 0; i < tableDataList.value.spareMaterialVos.length; i++) {
      if (!String(tableDataList.value.spareMaterialVos[i].payNetworkPrice)) {
        ElMessage({
          type: 'error',
          message: `请输入第${i + 1}行的向服务商支付费用单价`,
        })
        checkResult = false
        break
      }

      if (
        !String(tableDataList.value.spareMaterialVos[i].receiveFactoryPrice) &&
        tableDataList.value.spareMaterialVos[i].type === 1
      ) {
        ElMessage({
          type: 'error',
          message: `请输入第${i + 1}行的收取商家费用单价`,
        })
        checkResult = false
        break
      }
    }

    if (checkResult) {
      saveLoading.value = true
      for (const key in tableDataList.value.spareMaterialVos) {
        let imgobj = tableDataList.value.spareMaterialVos[key]
        let arrimg = []
        if (imgobj.images.length > 0) {
          for (const i in imgobj.images) {
            arrimg.push(imgobj.images[i].file)
          }
          if (imgobj.images[0].file) {
            const res = await orderAnnexUpload(arrimg)
            imgobj.images = res.data.data.rows.map((o) => ({ id: null, image: o }))
          }
        }
      }
      const addr = addrsDom.value.getSelectAddr()
      tableDataList.value.receiptProvince = addr.province
      tableDataList.value.receiptCity = addr.city
      tableDataList.value.receiptArea = addr.area
      tableDataList.value.receiptTown = addr.town
      if (tableDataList.value.type == 1) {
        tableDataList.value.networkSpareType = 1
      }
      tableDataList.value.workId = props.workId
      tableDataList.value.spareMaterialVos = tableDataList.value.spareMaterialVos.map((item) => {
        const __item = _.cloneDeep(item)
        delete __item.partSpecOptions
        return __item
      })
      const res = await spareSaveOrder(tableDataList.value)
      if (res.data.success) {
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'success',
          offset: 200,
        })
        emits('update-list')
        onCancel()
      } else {
        if (res.data.isError)
          ElMessage({
            showClose: true,
            message: res.data.message,
            duration: 4000,
            offset: 200,
            type: 'error',
          })
      }
      saveLoading.value = false
    }
  }

  /**
   * 删除文件
   * @param {number} rowIndex - 操作的表格行的索引
   * @param {number} imgIndex - 文件索引
   */
  const handleDelFile = (rowIndex: number, imgIndex: number) => {
    const imgs = tableDataList.value.spareMaterialVos[rowIndex].images.splice(imgIndex, 1)
    tableDataList.value.spareMaterialVos[rowIndex].delImageIds.push(imgs[0].id)
  }

  /**
   * 添加图片事件
   * @param {object} file - 文件
   * @param {number} index - 操作的表格行的索引
   */
  const handleUploadChange = async (file: UploadFile, index: number) => {
    if (tableDataList.value.spareMaterialVos[index].images.length >= 8) {
      ElMessage({
        showClose: true,
        message: '最多上传8个',
        duration: 4000,
        offset: 200,
        type: 'error',
      })
      return
    }
    tableDataList.value.spareMaterialVos[index].images.push({
      image: URL.createObjectURL(file.raw),
      file: file.raw,
    })
  }

  // 申请类型更新事件
  const handleChangeType = () => {
    if (tableDataList.value.type === 2) {
      tableDataList.value.receiptAddrType = 1
      tableDataList.value.networkSpareType = 1
    }
  }

  /**
   * 取消按钮事件
   */
  const onCancel = () => {
    tableDataList.value = {
      delSpareMaterialIds: [], // 删除的工单配件物料对象
      id: null, // 工单备件ID，新增不必传，修改必传
      networkSpareType: 1, // 服务商配件类型：1-服务商-外部仓配件，2-工程师-外部仓配件，3-自购备件
      receiptAddrType: 1, // 收货地址类型：1-工单客户地址，2-服务商地址
      receiptAddress: '', // 收货人详细地址
      receiptArea: '', // 收货地址-县/区
      receiptCity: '', // 收货地址-市
      receiptName: '', // 收货人姓名
      receiptPhone: '', // 收货人手机号
      receiptProvince: '', // 收货地址-省
      receiptTown: '', // 收货地址-镇
      remark: '', // 备注
      spareMaterialVos: [
        // 工单配件物料对象
        {
          delImageIds: [], //	删除的工单费用图片对象ID
          id: null, // 配件物料ID，新增不必传，修改必传
          images: [], // 工单服务费用图片对象
          model: '', // 物料型号
          name: '', // 物料名称
          overinsured: true, // 物料质保状态：false-保内，true-保外
          payNetworkPrice: 0, // 	向服务商支付费用
          price: 0, // 物料单价
          qty: 1, // 物料数量
          receiveFactoryPrice: 0, // 收取商家费用
          remark: '', // 备注
          spareId: null, //	物料配件ID
          specId: null, // 物料配件规格ID
          specName: '', // 物料配件规格名称
          specSku: '', //商品规格编号
          type: 1, // 收支类型：1-向服务商支付，2-商家收取，3-平台承担
        },
      ],
      type: 1, // 申请类型：1-商家/总部配件，2-外部配件
      userOrNetworkId: null, // 用户/网点ID
      workId: null, // 工单ID
    }
    visible.value = false
  }

  /**
   * 收取商家费用输入框输入事件
   * @param {Event} e - input输入元素
   * @param {number} index - 表格操作的行的索引
   */
  const handleReceiveFactoryPriceInput = (e: Event, index: number) => {
    checkNum(e)

    // 防止输入频繁输入会出现三位小数的问题
    tableDataList.value.spareMaterialVos[index].receiveFactoryPrice = (
      e.target as HTMLInputElement
    ).value

    // 限制金额的最大值为9999999999.99
    ;(e.target as HTMLInputElement).value = keepPartInteger(
      (e.target as HTMLInputElement).value,
      10,
    )
  }

  /**
   * 向服务商支付费用输入框输入事件
   * @param {Event} e - Event
   * @param {number} index - 表格操作的行的索引
   */
  const handlePayNetworkPricePriceInput = (e: Event, index: number) => {
    checkNum(e)

    // 防止输入频繁输入会出现三位小数的问题
    tableDataList.value.spareMaterialVos[index].payNetworkPrice = (
      e.target as HTMLInputElement
    ).value

    // 限制金额的最大值为9999999999.99
    ;(e.target as HTMLInputElement).value = keepPartInteger(
      (e.target as HTMLInputElement).value,
      10,
    )
  }

  /**
   * 平台承担费用输入框输入事件
   * @param {Event} e - Event
   * @param {number} index - 表格操作的行的索引
   */
  const handlePriceInput = (e: Event, index: number) => {
    checkNum(e)

    // 防止输入频繁输入会出现三位小数的问题
    tableDataList.value.spareMaterialVos[index].price = (e.target as HTMLInputElement).value

    // 限制金额的最大值为9999999999.99
    ;(e.target as HTMLInputElement).value = keepPartInteger(
      (e.target as HTMLInputElement).value,
      10,
    )
  }
</script>

<style lang="scss" scoped>
  @import './ApplyPart.scss';
</style>
